import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  }, {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Login.vue'),
    meta: {
      isPublic: true
    }
  }, {
    path: '/register',
    name: 'register',
    component: () => import('@/views/Register.vue'),
    meta: {
      isPublic: true
    }
  }
  // {
  // path: '/about',
  // name: 'About',
  // route level code-splitting
  // this generates a separate chunk (about.[hash].js) for this route
  // which is lazy-loaded when the route is visited.
  // component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  // }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach(async (to, from, next) => {
  // 跳转是授权页面, 没有token的时候
  if (!to.meta.isPublic && !localStorage.getItem('token')) {
    next('/login')
  } else if (!to.meta.isPublic && localStorage.getItem('token')) {
    const res = await Vue.prototype.$http.get('/admin/auth')
    if (res.error !== -1) {
      next()
    }
  } else next()
})

export default router
